#from django import http
from django.http import HttpResponseForbidden
from django.http import JsonResponse
from django.shortcuts import render,redirect
import re
from apps.users.models import User
from django.urls import reverse
from django.views import View
# Create your views here.

from django.contrib.auth import login

#2 判断用户名是否重复注册
class UsernameCountView(View):

    def get(self,request,username):

        #1.校验正则是否符合

        #  2.去数据库校验 count
        count = User.objects.filter(username=username).count()

        # 3.返回响应结果
        return JsonResponse({'code':'0', 'errmsg':'ok','count':count

        })

# 1 定义注册类视图
class RegisterView(View):
    # 1 显示注册页面
    def get(self,request):
        return render(request, "register.html")

    # 2 注册提交功能
    def post(self,request):

        # 1接受参数分析
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')

        # 2 校验参数 校验 判空 正则
        if not all([username,password,password2,mobile,allow]):
            #return http.HttpResponseForbidden('参数不齐')
            return HttpResponseForbidden('参数不全!')

        # 2.1 用户名
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return HttpResponseForbidden('请输入5-20个字符的用户名')

        # 2.2 校验密码
        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return HttpResponseForbidden('请输入8-20位的密码')

        # 2.3 校验二次密码
        if password2 != password:
            return HttpResponseForbidden('两次输入的密码不一致')
        # 2.4 校验手机号
        if not re.match(r'^1[345789]\b{9}$',mobile):
            return HttpResponseForbidden('您输入的手机号格式不正确')
        # 2.5 是否勾选同意协议
        if allow != 'no':
            return HttpResponseForbidden('请勾选用户同意!')

        # 3.注册用户数据
        try:
            user = User.objects.create_user(
                username=username,
                password=password,
                mobile=mobile,
            )
        except Exception as e:
             return render(request,'register.html',{'register_errmsg':'注册失败'})

        #  登录状态
        login(request, user)
        #return  redirect('/')
        return redirect(reverse('contents:index'))